import type { TaskStorage } from '../types/task';

/**
 * 导出数据到文件
 * @param data 任务数据
 */
export const exportToFile = (data: TaskStorage): void => {
  const json = JSON.stringify(data, null, 2);
  const blob = new Blob([json], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  
  const link = document.createElement('a');
  link.href = url;
  link.download = `task-progress-${new Date().toISOString().split('T')[0]}.json`;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};

/**
 * 从文件导入数据
 * @param file 文件对象
 * @returns Promise<TaskStorage>
 */
export const importFromFile = (file: File): Promise<TaskStorage> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (event) => {
      try {
        if (!event.target?.result) {
          throw new Error('Failed to read file');
        }
        
        const data = JSON.parse(event.target.result as string) as TaskStorage;
        
        // 简单验证导入的数据结构
        if (!data.tasks || !Array.isArray(data.tasks) || !data.version) {
          throw new Error('Invalid file format');
        }
        
        resolve(data);
      } catch (error) {
        reject(error);
      }
    };
    
    reader.onerror = () => {
      reject(new Error('Failed to read file'));
    };
    
    reader.readAsText(file);
  });
};